import cloud from '@lafjs/cloud'
import Pay from 'wechatpay-node-v3-laf';

import { changeStudentSource } from "@/admin/web/set_student_info";
import { changeOrderInfo } from "@/admin/web/set_order_info";

const pay = new Pay({
  appid: 'wx267097d752f5c3fd', // 认证服务号 appid
  mchid: '1593154581',  //  绑定该认证服务号的微信支付商户号
  publicKey: savePublicKey(), // V3 公钥 apiclient_cert.pem
  privateKey: savePrivateKey(), // V3 秘钥 apiclient_key.pem
});
const key = "3fa70dc6ee45b4e90b2ab0fdc24dd778" // 用商户平台上设置的 APIv3 密钥【微信商户平台—>账户设置—>API 安全—>设置 APIv3 密钥】

export default async function (ctx: FunctionContext) {
  const { resource } = ctx.body
  const { ciphertext, associated_data, nonce } = resource
  const result = pay.decipher_gcm(ciphertext, associated_data, nonce, key);
  if (result.trade_state == "SUCCESS") {
    console.log("微信支付成功", result);
    //先判断一下是否是支付尾款
    let ret = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { balance_out_trade_no: result.out_trade_no },
    });
    if (ret && ret._id) return await balancePaySuccess(ret, result)


    let { curriculum_id } = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: result.out_trade_no },
    });

    let { type } = await cloud.nw.db.findByWhereJson({
      dbName: "web-course",
      whereJson: { _id: curriculum_id },
    });

    let resp = await cloud.nw.db.findByWhereJson({
      dbName: "web-curriculum",
      whereJson: { _id: type[0] },
    });

    let status
    if (resp.hasOwnProperty("isExamine") && resp.isExamine == 1) {  //需要审核
      status = 1
    } else {
      status = 2  //报名成功
    }

    // 支付成功的逻辑
    await cloud.nw.db.update({
      dbName: "web-order",
      whereJson: { out_trade_no: result.out_trade_no },
      dataJson: {
        status,
        pay_info: {
          pay_time: result.success_time, //支付成功时间
          pay_amount: result.amount,  //单位是分，前端展示的时候要/100 
          trade_type: result.trade_type,
          transaction_id: result.transaction_id,
          bank_type: result.bank_type,
        }
      }
    });

    //修改订单状态
    changeOrderInfo({ out_trade_no: result.out_trade_no });

    changeStudentSource(result.out_trade_no); // 改变学生来源
  }


  return `<xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
</xml>`
}


//尾款支付成功逻辑
async function balancePaySuccess(ret, result) {
  await changeOrderInfo({ _id: ret._id });
  await cloud.nw.db.update({
    dbName: "web-order",
    whereJson: { _id: ret._id },
    dataJson: {
      status: 2,
      balance_pay_info: {
        pay_time: result.success_time, //支付成功时间
        pay_amount: result.amount, //单位是分，前端展示的时候要/100 
        trade_type: result.trade_type,
        transaction_id: result.transaction_id,
        bank_type: result.bank_type,
      }
    }
  });
}



function savePublicKey() {
  const key = `
-----BEGIN CERTIFICATE-----
MIIEKDCCAxCgAwIBAgIUNLJk3hYaWOL+VX9SbvbOxXRrZ3owDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjMwNzE5MDk0NjQ4WhcNMjgwNzE3MDk0NjQ4WjCBgTETMBEGA1UEAwwK
MTU5MzE1NDU4MTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQL
DCTkuIrmtbfkupror5rln7norq3lrabmoKHmnInpmZDlhazlj7gxCzAJBgNVBAYM
AkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAJ/auEoRpI0odU2LhVYPvOmo1wzc7c090vLEBHiJ73p4LMvO/HOlRjY7
LTfIDqqhZ9Xoqe9o3a6o1ameDTjVbXUxRkhHTtsrJdq5ql8rPVf7lolrmquWyI0/
f+vNKirEJO3JIq6h5Mbb+7tCmKlNnsvtHPL/qkjaBuvnd/uDEISt/IjYWxvOFJee
o55QMy+rbgTC0kKdiVKLenstG/jipPqXQw19lRjullf/RIntZ2xR9lA63E2li+tF
diC8ODrtjru1w+/R7WS+zQXLmvGTzaxAQDf5q+keN+yf7T5OvOtLmEoqI6UREN8J
kxXv0xN4kDfLIR0izbiD2xsMibYvXXMCAwEAAaOBuTCBtjAJBgNVHRMEAjAAMAsG
A1UdDwQEAwID+DCBmwYDVR0fBIGTMIGQMIGNoIGKoIGHhoGEaHR0cDovL2V2Y2Eu
aXRydXMuY29tLmNuL3B1YmxpYy9pdHJ1c2NybD9DQT0xQkQ0MjIwRTUwREJDMDRC
MDZBRDM5NzU0OTg0NkMwMUMzRThFQkQyJnNnPUhBQ0M0NzFCNjU0MjJFMTJCMjdB
OUQzM0E4N0FEMUNERjU5MjZFMTQwMzcxMA0GCSqGSIb3DQEBCwUAA4IBAQAr6mQ7
8LJ1QvvTjMuMJ11UrgKf5wSawuJiL6MfetVBB51JwGKBfBJ/KgBsWrms+Eg38lZZ
QKDgwkLE/PfqEzB9NSjQkZvmpOfx6+KAXBAYrMngDwATIESgJAPFo4g/cowDpvaC
noNWvNHIZCR2whi29Zy8xoKONme944rYEYWFm1M06scglWuo2mo4Wk6/SiAVh6JO
91XJM0P+SxZV7CQ5K8aIpqUcppRk54MDujrLJB8lRVHUNWhcRzj7H6cMmfoY/H+a
CsocVeEBcwhbffZLaYhr7He60D3O2ADTZFRNr73dDb4zEDRrxhRjKHQDO7enUzc0
Vgj5ab17makmBtvs
-----END CERTIFICATE-----  
`;
  return Buffer.from(key);
}

function savePrivateKey() {
  const key = `
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCf2rhKEaSNKHVN
i4VWD7zpqNcM3O3NPdLyxAR4ie96eCzLzvxzpUY2Oy03yA6qoWfV6KnvaN2uqNWp
ng041W11MUZIR07bKyXauapfKz1X+5aJa5qrlsiNP3/rzSoqxCTtySKuoeTG2/u7
QpipTZ7L7Rzy/6pI2gbr53f7gxCErfyI2FsbzhSXnqOeUDMvq24EwtJCnYlSi3p7
LRv44qT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